

package com.sui.bigdata.flink.sql.core.side;

import com.sui.bigdata.flink.sql.core.enums.ECacheType;
import com.sui.bigdata.flink.sql.core.metric.JoinLastMinCostAvg;
import com.sui.bigdata.flink.sql.core.metric.MetricConstant;
import com.sui.bigdata.flink.sql.core.side.cache.AbsSideCache;
import com.sui.bigdata.flink.sql.core.side.cache.CacheObj;
import com.sui.bigdata.flink.sql.core.side.cache.LRUSideCache;
import org.apache.calcite.sql.JoinType;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Counter;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.flink.streaming.api.operators.async.queue.StreamRecordQueueEntry;
import org.apache.flink.types.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;

/**
 * All interfaces inherit naming rules: type + "" such as == "Mysql
 * Date: 2019/07/10
 *
 * @author yong_chen@sui.com
 */

public abstract class AsyncReqRow extends RichAsyncFunction<Row, Row> implements ISideReqRow {

    private static final long serialVersionUID = 2098635244857937717L;
    private static final Logger LOG = LoggerFactory.getLogger(AsyncReqRow.class);

    protected SideInfo sideInfo;

    protected  transient Counter asyncTimeOutRecords;

    protected  transient Counter joinFailRecords;

    protected transient JoinLastMinCostAvg joinLastMinCostAvg;



    public AsyncReqRow(SideInfo sideInfo) {
        this.sideInfo = sideInfo;
    }

    public void initMetric(){
        asyncTimeOutRecords = getRuntimeContext().getMetricGroup().counter(MetricConstant.ASYNC_TIME_OUT_RECORDS);
        joinLastMinCostAvg =   getRuntimeContext().getMetricGroup().meter(MetricConstant.JOIN_COST_AVG, new JoinLastMinCostAvg());
        joinFailRecords = getRuntimeContext().getMetricGroup().counter(MetricConstant.JOIN_FAIL_RECORDS);

    }

    @Override
    public void timeout(Row input, ResultFuture<Row> resultFuture) throws Exception {
        asyncTimeOutRecords.inc();
        LOG.error("Async function call has timed out,record: {}.", input.toString());

    }

    private void initCache() {
        SideTableInfo sideTableInfo = sideInfo.getSideTableInfo();
        if (sideTableInfo.getCacheType() == null || ECacheType.NONE.name().equalsIgnoreCase(sideTableInfo.getCacheType())) {
            return;
        }

        AbsSideCache sideCache;
        if (ECacheType.LRU.name().equalsIgnoreCase(sideTableInfo.getCacheType())) {
            sideCache = new LRUSideCache(sideTableInfo);
            sideInfo.setSideCache(sideCache);
        } else {
            throw new RuntimeException("not support side cache with type:" + sideTableInfo.getCacheType());
        }

        sideCache.initCache();
    }

    protected CacheObj getFromCache(String key) {
        return sideInfo.getSideCache().getFromCache(key);
    }

    protected void putCache(String key, CacheObj value) {
        sideInfo.getSideCache().putCache(key, value);
    }

    protected boolean openCache() {
        return sideInfo.getSideCache() != null;
    }

    protected void dealMissKey(Row input, ResultFuture<Row> resultFuture) {
        if (sideInfo.getJoinType() == JoinType.LEFT) {
            //Reserved left table data
            Row row = fillData(input, null, null);
            resultFuture.complete(Collections.singleton(row));
        } else {
            resultFuture.complete(null);
        }
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        initCache();
    }

    @Override
    public void close() throws Exception {
        super.close();
    }
}
